package com.whxy02.tolearn.app.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whxy02.tolearn.app.beans.*;
import com.whxy02.tolearn.app.resultObject.ResultState;
import com.whxy02.tolearn.app.resultObject.OneQuestionType;
import com.whxy02.tolearn.app.resultObject.QuestionResultType;
import com.whxy02.tolearn.app.service.*;
import com.whxy02.tolearn.app.utils.PackResult;
import com.whxy02.tolearn.app.utils.Split;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/question")
public class QuestionPage {

    @Resource
    SubjectService subjectService;
    @Resource
    TagsService tagsService;
    @Resource
    QuestionTypeService questionTypeService;
    @Resource
    QuestionService questionService;
    @Resource
    PackResult packResult;
    @Resource
    Split split;
    @Resource
    ExamService examService;
    @Resource
    AnswerService answerService;
    @Resource
    HistoryService historyService;
    @Resource
    CommentService commentService;


    /**
     * 生成试卷
     *
     * @param request
     * @param subjectId
     * @param tagsId
     * @param grade
     * @return
     */
    @RequestMapping("/search/generate")
    public Map<String, Object> searchQuestion(HttpServletRequest request, @RequestParam(value = "subjectId") Integer subjectId
            , @RequestParam(value = "tagsId", required = false, defaultValue = "0") Integer tagsId, @RequestParam(value = "grade", required = false) String grade) {

        QuestionResultType result = new QuestionResultType();
        List<Question> questions;
        try {
            List<QuestionType> questionTypes = questionTypeService.getBySubject(subjectId);
            if (questionTypes != null) {
//                for (QuestionType questionType : questionTypes) {
//                    if(questionType.getQuestionCount()>10){
//                        result.addQuestionInfos(questionType.getTypeName(), 10);
//                    }else {
//                        result.addQuestionInfos(questionType.getTypeName(), questionType.getQuestionCount());
//                    }
//
//                }
                if (tagsId == null||tagsId == 0  ) {
                    questions = questionService.getByLimit(subjectId, result);
                    for (Question question : questions) {
                        question.setContent(split.getContent(question.getQuestionId()));

                    }
                    result.setQuestions(questions);
                } else {
                    questions = questionService.getByLimit(subjectId, tagsId, result);
                    for (Question question : questions) {
                        question.setContent(split.getContent(question.getQuestionId()));
                    }
                    result.setQuestions(questions);
                }
                String questionId = "";
                for (Question q : result.getQuestions()) {
                    questionId += q.getQuestionId() + "@@";
                }
                HttpSession session = request.getSession();
                session.setAttribute("questionId", questionId);
                if (result.getQuestions().size() == 0) {
                    return packResult.doPackToMap(ResultState.NULL_QUESTION, null);
                }
                return packResult.doPackToMap(ResultState.SUCCESS, result);
            } else {
                return packResult.doPackToMap(ResultState.NOT_FOUND_ELIGIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR, e);
        }
    }

    /**
     * 查询subject或者subject下的tags或者exam
     *
     * @param target
     * @param id
     * @return
     */
    @RequestMapping("/search/{target}")
    public Map<String, Object> search(@PathVariable("target") String target, @RequestParam(value = "id", required = false) Integer id) {
        try {
            switch (target) {
                case "subject":
                    return packResult.doPackToMap(ResultState.SUCCESS, subjectService.getAll());
                case "tags":
                    return packResult.doPackToMap(ResultState.SUCCESS, tagsService.getBySubjectId(id));
                case "grade":
                    return null;
                case "exam":
                    QuestionResultType result = new QuestionResultType();
                    Exam exam = examService.getById(id);
                    if (exam != null) {
                        String questionId = exam.getQuestionId();
                        List<Integer> questionIds = split.getQuestionId(questionId);

                        result.setQuestions(questionService.getByIds(questionIds));
                        result.setTitle(exam.getTitle());
                    } else {
                        return packResult.doPackToMap(ResultState.NOT_FOUND_EXAM);
                    }
                    return null;
                default:
                    return null;

            }
        } catch (Exception e) {
            return packResult.doPackToMap(ResultState.SERVER_ERR, e);
        }
    }

    /**
     * 将生成的exam插入数据库
     *
     * @param grade
     * @param level
     * @param title questionId       1@@2@@3
     * @return
     */
    @RequestMapping("/search/generate/createExam")
    public Map<String, Object> createExam(HttpServletRequest request, @RequestParam(value = "grade", required = false) String grade, @RequestParam(value = "level", required = false) String level, @RequestParam(value = "title", required = false, defaultValue = "模拟试卷") String title) {
        ArrayList<Integer> ids;
        HttpSession session = request.getSession();
        String questionId = (String) session.getAttribute("questionId");
        try {
            ids = new ArrayList<>();
            for (String s : questionId.split("@@")) {
                if (!s.equals("")) {
                    ids.add(Integer.parseInt(s));
                }
            }
        } catch (Exception e) {
//            System.out.println(questionId);
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.QUESTION_ID_FIELD);
        }

        try {
            Exam exam = examService.getByQuestion(questionId);
            if (exam == null) {
                exam = new Exam();
                exam.setGrade(grade);
                exam.setLevel(level);
                exam.setTitle(title);
                ArrayList<Answer> answers = new ArrayList<>();
                questionId = "";

                for (Integer id : ids) {
                    Answer a = answerService.getByQuestionId(id);
                    if (a != null) {
                        questionId += id + "@@";
                        answers.add(answerService.getByQuestionId(id));
                    }
                }

                if (!answers.isEmpty()) {
                    String s = "";
                    int i = 1;
                    for (Answer answer : answers) {
                        s = s + i + "、答案：" + answer.getAnswer() + "\n解析：" + answer.getAnalysis() + "@@";
                        i++;
                    }
                    exam.setAnalysis(s);
                }

                exam.setSubjectId(questionService.getById(ids.get(0)).getSubjectId());
                exam.setTagsId(questionService.getById(ids.get(0)).getTagsId());
                exam.setQuestionId(questionId);
                examService.save(exam);
                session.setAttribute("examId", exam.getExamId());
                return packResult.doPackToMap(ResultState.SUCCESS);
            } else {
                session.setAttribute("examId", exam.getExamId());
                return packResult.doPackToMap(ResultState.EXIST_EXAM);
            }
        } catch (Exception e) {

            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR, e);
        }

    }

    @RequestMapping("/history/add")
    public Map<String, Object> addHistory(HttpServletRequest request, @RequestParam("totalScore") Double totalScore) {
        HttpSession session = request.getSession();
        Integer examId = (Integer) session.getAttribute("examId");
        User user = (User) request.getAttribute("user");
        try {
            Exam exam = examService.getById(examId);
            if (exam == null) {
                return packResult.doPackToMap(ResultState.NOT_FOUND_EXAM);
            }

            History history = new History();
            history.setResult("" + totalScore);
            history.setUserId(user.getUserId());
            history.setTitle(exam.getTitle());
            history.setTagsId(exam.getTagsId());
            history.setSubjectId(exam.getSubjectId());
            history.setLevel(exam.getLevel());
            history.setExamId(examId);
            if (totalScore >= 60) {
                history.setMark(true);
            } else {
                history.setMark(false);
            }

            historyService.save(history);

            return packResult.doPackToMap(ResultState.SUCCESS, history);

        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR, e);
        }


    }

    @RequestMapping("/score/check")
    public Integer toScore(HttpServletRequest request, @RequestParam("qId") String qId, @RequestParam("myAnswer") String myAnswer) {
        User user = (User) request.getAttribute("user");
        Integer questionId = Integer.parseInt(qId.replace("q", ""));
        String[] myAnswers = myAnswer.split("@@");
        try {
            Answer answer = answerService.getByQuestionId(questionId);
            if (answer != null) {
                List<String> answers = Arrays.asList(answer.getAnswer());
                for (String a : myAnswers) {
                    if (!answers.contains(a)) {
                        return 0;
                    }
                }
                return 1;
            } else {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 添加评论
     *
     * @param request
     * @param details
     * @return
     */
    @RequestMapping("/comment/add")
    public Map<String, Object> doComment(HttpServletRequest request, @RequestParam("questionId") Integer questionId, @RequestParam("details") String details) {
        User user = (User) request.getAttribute("user");
        Comment comment = new Comment();
        comment.setDetails(details);
        comment.setUserId(user.getUserId());
        try {
            commentService.save(comment);
            Question question = questionService.getById(questionId);
            question.setCommentId(question.getCommentId() + comment.getCommentId() + "@@");
            questionService.change(question);
            return packResult.doPackToMap(ResultState.SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR, e);
        }

    }

    /**
     * 获取一个科目的所有题目
     *
     * @param nowPage
     * @param subjectId
     * @param tagsId
     * @return
     */
    @RequestMapping("/searchAll/{nowPage}")
    public Map<String, Object> getAll(@PathVariable("nowPage") Integer nowPage, @RequestParam("subjectId") Integer subjectId, @RequestParam(value = "tagsId", required = false) Integer tagsId) {


        try {
            if (tagsId != null) {
                Page<Question> page = questionService.getByPage(nowPage, subjectId, tagsId);
                for (Question question : page.getRecords()) {
                    question.setContent(split.getContent(question.getQuestionId()));
                    question.setAnswer(split.getAnswer(question.getQuestionId()));
                }
                if(page.getTotal()==0){
                    return packResult.doPackToMap(ResultState.NOT_HAS_QUESTION);
                }

                return packResult.doPackToMap(ResultState.SUCCESS, page);
            } else {
                Page<Question> page = questionService.getByPage(nowPage, subjectId);
                for (Question question : page.getRecords()) {
                    question.setContent(split.getContent(question.getQuestionId()));
                    question.setAnswer(split.getAnswer(question.getQuestionId()));
                }

                if(page.getTotal()==0){
                    return packResult.doPackToMap(ResultState.NOT_HAS_QUESTION);
                }

                return packResult.doPackToMap(ResultState.SUCCESS, page);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR, e);
        }

    }


    @RequestMapping("/getOne/{questionId}")
    public Map<String, Object> getOne(HttpServletRequest request, @PathVariable("questionId") Integer questionId) {

        OneQuestionType result = new OneQuestionType();
        try {
            Question question = questionService.getById(questionId);

            if (question == null) {
                return packResult.doPackToMap(ResultState.NOT_FOUND_QUESTION);
            }

            result.setComments(split.getComment(question));
            QuestionType questionType = questionTypeService.getById(question.getTypeId());
            if (questionType != null){
               setDisplay(question,questionType);
            }


            Tags tags = tagsService.getById(question.getTagsId());
            if (tags != null)
                question.setTags(tags.getTagsName());

            Subject subject = subjectService.getById(question.getSubjectId());
            if (subject != null)
                question.setSubject(subject.getSubjectName());

            question.setContent(split.getContent(questionId));

            question.setAnswer(split.getAnswer(questionId));
            result.setQuestion(question);
            return packResult.doPackToMap(ResultState.SUCCESS, result);
        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR, e);
        }

    }

    @RequestMapping("/searchExam/{examId}")
    public Map<String,Object> getExam(@PathVariable("examId")Integer examId){
        try {
            Exam exam= examService.getById(examId);
            if(exam==null){
                return packResult.doPackToMap(ResultState.NOT_FOUND_EXAM);
            }
            List<Integer> questionIds=split.getQuestionId(exam.getQuestionId());
            QuestionResultType result=new QuestionResultType();
            List<Question> questions= questionService.getByIds(questionIds);
            for(Question q:questions){
                if (q!=null){
                    QuestionType questionType= questionTypeService.getById(q.getTypeId());
                    if(questionType!=null){
                        setDisplay(q,questionType);
                    }
                    q.setContent(split.getContent(q.getQuestionId()));
                }
            }

            result.setQuestions(questions);
            result.setTitle(exam.getTitle());

            return packResult.doPackToMap(ResultState.SUCCESS,result);

        } catch (Exception e) {
            e.printStackTrace();
            return packResult.doPackToMap(ResultState.SERVER_ERR,e);
        }
    }

    private void setDisplay(Question question,QuestionType questionType){
        if(questionType.getTypeName().equals("单选题")){
            question.setDisplay(1);
        }
        else if(questionType.getTypeName().equals("多选题")){
            question.setDisplay(2);
        }
        else if(questionType.getTypeName().equals("填空题")){
            question.setDisplay(3);
        }
    }

}
